/**
 * Project: springyounger.lottery.web
 * 
 * File Created at 2010-4-10
 * $Id$
 * 
 * Copyright 2009 Zjut Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Zjut Edu. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Zjut Edu.
 */
package com.springyouner.lottery.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.displaytag.util.ParamEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.springyouner.lottery.tools.LotteryUtil;
import com.springyounger.lottery.dal.dataobject.LotteryPhase;
import com.springyounger.lottery.dal.dataobject.LotteryPhaseQuestion;
import com.springyounger.lottery.dal.dataobject.LotteryPrizeQuota;
import com.springyounger.lottery.dal.dataobject.LotteryQuestion;
import com.springyounger.lottery.service.PrizeService;
import com.springyounger.lottery.service.user.PhaseService;
import com.springyounger.lottery.service.user.QuestionService;

/**
 * AdminPhaseController
 * 
 * @author springyounger
 */
public class AdminPhaseController extends MultiActionController {
	private static final Logger logger = LoggerFactory
			.getLogger(AdminPhaseController.class);
	private PhaseService phaseService;
	private PrizeService prizeService;
	private QuestionService questionService;

	public ModelAndView displayInsert(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return new ModelAndView("admin/phaseInsertAndUpdate");
	}

	/**
	 * 查看活动题目
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ModelAndView displayPhaseQuestion(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map model = new HashMap();
		String id = request.getParameter("id");
		if (LotteryUtil.isEmpty(id) || !LotteryUtil.isNumeric(id)) {
			logger.info("活动id异常!");
			return findByAll(request, response);
		}

		int phaseId = Integer.parseInt(id);
		LotteryPhase phase = phaseService.getPhaseById(phaseId);

		// 页数的参数名
		String pageIndexName = new ParamEncoder("row")
				.encodeParameterName(org.displaytag.tags.TableTagParameters.PARAMETER_PAGE);
		// 每页显示的条数
		int pageSize = 10;
		// 当前页
		int pageIndex = LotteryUtil
				.isEmpty(request.getParameter(pageIndexName)) ? 0 : (Integer
				.parseInt(request.getParameter(pageIndexName)) - 1);
		// 总记录
		int resultSize = questionService.getAllPhaseQuestionCount(phase
				.getPhaseId());

		List<LotteryPhaseQuestion> phaseQuestionList = questionService
				.getAllPhaseQuestion(phase.getPhaseId(), pageIndex, pageSize);

		if (logger.isDebugEnabled()) {
			logger.debug("查看题目,总数{}", resultSize);
		}
		model.put("phase", phase);
		model.put("phaseQuestionList", phaseQuestionList);
		model.put("resultSize", resultSize);
		return new ModelAndView("admin/phaseQuestionList", model);
	}

	@SuppressWarnings("unchecked")
	public ModelAndView findByAll(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 当前日期
		Date today = LotteryUtil.getToday();

		Map model = new HashMap();
		// 页数的参数名
		String pageIndexName = new ParamEncoder("row")
				.encodeParameterName(org.displaytag.tags.TableTagParameters.PARAMETER_PAGE);

		// 每页显示的条数
		int pageSize = 10;
		// 当前页
		int pageIndex = LotteryUtil
				.isEmpty(request.getParameter(pageIndexName)) ? 0 : (Integer
				.parseInt(request.getParameter(pageIndexName)) - 1);
		// 总记录
		int resultSize = phaseService.getAllPhaseCount();
		List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
		phaseList = phaseService.getPhases(pageIndex, pageSize);

		for (LotteryPhase phase : phaseList) {
			// 是否激活(正在活动中或者过期的设置为 y,未开始的设置为 n)
			if (LotteryUtil.getQuot(today, phase.getGmtStart()) > 0) {
				phase.setIsActivity("n");

				// 检查活动题目是否已经生成
				if (!questionService.getPhaseQuestionCount(phase.getPhaseId())) {
					// 题目没有生成
					phase.setHaveQuestion("n");
				} else {
					// 活动题目已生成
					phase.setHaveQuestion("y");
				}

				// 检查是否已经创建奖品配额
				List<LotteryPrizeQuota> quotaList = prizeService
						.getAllPrizesByPhaseId(phase.getPhaseId());

				if (quotaList.size() != 0 && null != quotaList.get(0)) {
					// 取出一个奖品进行验证
					LotteryPrizeQuota quota = quotaList.get(0);
					LotteryPrizeQuota verifyQuota = prizeService
							.getTopPrizeQuota(quota.getPrizeId());
					if (null == verifyQuota) {
						// 没有创建配额,活动可用
						phase.setHaveQuota("n");
					} else {
						phase.setHaveQuota("y");
					}
				} else {
					phase.setHaveQuota("n");
				}
			} else {
				phase.setIsActivity("y");
			}
		}
		model.put("phaseList", phaseList);
		model.put("resultSize", resultSize);
		return new ModelAndView("admin/phaseList", model);
	}

	public ModelAndView findById(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");

		if (LotteryUtil.isEmpty(id) || !LotteryUtil.isNumeric(id)) {
			return findByAll(request, response);
		}

		int phaseId = Integer.parseInt(id);
		LotteryPhase phase = phaseService.getPhaseById(phaseId);
		return new ModelAndView("admin/phaseInsertAndUpdate", "phase", phase);
	}

	public ModelAndView insertAndUpdate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");

		String phaseName = request.getParameter("phaseName");

		String start = request.getParameter("gmtstart");
		String end = request.getParameter("gmtend");
		String daily = request.getParameter("dailyQuestion");
		String except = request.getParameter("exceptParticiants");

		LotteryPhase phase = new LotteryPhase();

		phase.setPhaseName(phaseName);
		Date gmtStart = LotteryUtil.stringToDate(start,
				LotteryUtil.DEFAULT_DATE_FORMAT);
		phase.setGmtStart(gmtStart);
		Date gmtEnd = LotteryUtil.stringToDate(end,
				LotteryUtil.DEFAULT_DATE_FORMAT);
		phase.setGmtEnd(gmtEnd);

		// 当前日期
		Date today = LotteryUtil.getToday();
		// 是否激活(正在活动中或者过期的设置为 y,未开始的设置为 n)
		if (LotteryUtil.getQuot(today, gmtStart) > 0) {
			// 未开始
			phase.setIsActivity("n");
		} else {
			phase.setIsActivity("y");
		}
		if (LotteryUtil.isEmpty(daily) || !LotteryUtil.isNumeric(daily)
				|| LotteryUtil.isEmpty(except)
				|| !LotteryUtil.isNumeric(except)) {
			return findByAll(request, response);
		}

		int dailyQuestion = Integer.parseInt(daily);
		int exceptParticiants = Integer.parseInt(except);
		phase.setDailyQuestion(dailyQuestion);
		phase.setExceptParticiants(exceptParticiants);

		if (id.equals("") || id.equals("0")) {
			// 判断是否已经存在
			if (phaseService.isExistPhase(phaseName.trim())) {
				return new ModelAndView("admin/phaseInsertAndUpdate",
						"message", "活动已存在");
			}
			// 创建
			phaseService.insertPhase(phase);
		} else {
			LotteryPhase verifyPhase = phaseService.getPhaseById(Integer
					.parseInt(id));
			if (!phaseName.equals(verifyPhase.getPhaseName())) {
				// 判断是否已经存在
				if (phaseService.isExistPhase(phaseName.trim())) {
					return new ModelAndView("admin/phaseInsertAndUpdate",
							"message", "活动已存在");
				}
			}
			// 修改
			phase.setPhaseId(Integer.parseInt(id));
			phaseService.updatePhase(phase);
		}
		return findByAll(request, response);
	}

	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		if (LotteryUtil.isEmpty(id) || !LotteryUtil.isNumeric(id)) {
			logger.info("活动id异常");
			return findByAll(request, response);
		}
		int phaseId = Integer.parseInt(id);

		// 级联删除
		phaseService.deletePhaseById(phaseId);

		return findByAll(request, response);
	}

	@SuppressWarnings("unchecked")
	public ModelAndView antuGenerate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String message = null;
		Map model = new HashMap();
		List<LotteryPhaseQuestion> phaseQuestionList = null;

		// 自动生成题目
		String id = request.getParameter("id");
		if (LotteryUtil.isEmpty(id) || !LotteryUtil.isNumeric(id)) {
			logger.info("活动id异常");
			return findByAll(request, response);
		}
		int phaseId = Integer.parseInt(id);

		// 活动信息
		LotteryPhase phase = phaseService.getPhaseById(phaseId);

		// 检查是否已经生成题目
		if (questionService.getPhaseQuestionCount(phase.getPhaseId())) {
			logger.info("该活动题目已生成");
			// 题目已生成
			message = "该活动题目已生成";

			model.put("phase", phase);
			model.put("message", message);
			return new ModelAndView("admin/autoGenerate", model);
		}

		phaseQuestionList = antuGenerate(phase);

		if (null != phaseQuestionList) {
			// 批量插入
			if (questionService.batchInsertPhaseQuestion(phaseQuestionList)) {
				message = "自动生成题目成功";
			} else {
				message = "自动生成题目失败";
			}
		} else {
			logger.info("题库中题目数量不足");
			message = "题库中题目数量不足";
		}

		// 显示题目
		model.put("phase", phase);
		model.put("phaseQuestionList", phaseQuestionList);
		model.put("message", message);

		return new ModelAndView("admin/autoGenerate", model);
	}

	/**
	 * 自动生成题目
	 * 
	 * @param phase
	 * @return
	 */
	private List<LotteryPhaseQuestion> antuGenerate(final LotteryPhase phase) {
		List<LotteryPhaseQuestion> phaseQuestionList = new ArrayList<LotteryPhaseQuestion>();
		boolean flag;

		// 目前只有选择题
		// 计算总题目数
		int quot = LotteryUtil.getQuot(phase.getGmtStart(), phase.getGmtEnd()) + 1;
		int questionAmount = quot * phase.getDailyQuestion();

		// 题库中总题目数
		int questionInStock = questionService.getAllQuestionCount();

		if (questionAmount > questionInStock) {
			// 题目数不够
			phaseQuestionList = null;
			flag = false;
		} else {
			// 检查某种题型的数量
			int selectInStock = questionService
					.getAllQuestionCountByType(LotteryQuestion.selectType);

			// 选择题
			if (questionAmount > selectInStock) {
				// 选择题目数目不够
				phaseQuestionList = null;
				flag = false;
			} else {
				flag = true;
			}
		}

		// 符合条件,进入题目生成流程
		if (flag) {
			// 取出某个题型的所有题目
			List<LotteryQuestion> questionList = questionService
					.getAllQuestionByType(LotteryQuestion.selectType);

			// 选择题型题目总数
			int random[] = new int[questionAmount];
			boolean another;
			LotteryQuestion question = null;
			Date today = phase.getGmtStart();

			for (int i = 0; i < questionAmount; i++) {
				// 生成questionAmount个题
				another = true;
				// 随机选择一个list的编号
				random[i] = (int) (Math.random() * questionList.size());
				for (int j = 0; j < i; j++) {
					// 检查选取的,是否是同一个编号
					if (random[i] == random[j]) {
						another = false;
						i--;
						break;
					}
				}
				// 得到一个题目
				if (another) {
					// 随机题目
					question = questionList.get(random[i]);
					if (null != question) {
						// 设置活动题目
						LotteryPhaseQuestion phaseQuestion = new LotteryPhaseQuestion();
						phaseQuestion.setPhaseQuestionId(question
								.getQuestionId());
						phaseQuestion.setQuestionType(question
								.getQuestionType());
						phaseQuestion.setQuestionLevel(Integer
								.parseInt(question.getQuestionLevel()));
						phaseQuestion.setQuestionContent(question
								.getQuestionContent());

						// 活动id
						phaseQuestion.setPhaseId(phase.getPhaseId());
						// 设置发布编号
						String sn = String.valueOf(i % phase.getDailyQuestion()
								+ 1);
						phaseQuestion.setPublishSn(sn);

						// 设置发布时间
						phaseQuestion.setPublishDate(today);

						// 第二天的题
						if (((i + 1) % phase.getDailyQuestion()) == 0) {
							today = LotteryUtil.addDays(today, 1);
						}

						// 添加题目
						phaseQuestionList.add(phaseQuestion);
					}
				}
			}
		}

		return phaseQuestionList;
	}

	/**
	 * @param phaseService
	 *            the phaseService to set
	 */
	public void setPhaseService(PhaseService phaseService) {
		this.phaseService = phaseService;
	}

	/**
	 * @param prizeService
	 *            the prizeService to set
	 */
	public void setPrizeService(PrizeService prizeService) {
		this.prizeService = prizeService;
	}

	/**
	 * @param questionService
	 *            the questionService to set
	 */
	public void setQuestionService(QuestionService questionService) {
		this.questionService = questionService;
	}
}
